<template>
	<view class="container">
		<!-- 顶部搜索框 -->
		<view class="search-container">
			<view class="search-bar" @click="navigateToSearch">
				<text class="iconfont">&#xe61b;</text>
				<text class="placeholder">搜索商品</text>
			</view>
		</view>
		<!-- 轮播图 -->
		<view>
			<swiper indicator-dots autoplay interval="3000" duration="500" class="banner-swiper" style="z-index: 10;">
				<swiper-item v-for="item in bannerList" :key="item.id">
					<image :src="item.cover" mode="scaleToFill" class="banner-image"></image>
				</swiper-item>
			</swiper>
		</view>

		<!-- 金刚区 -->
		<view class="kingkong-container">
			<view class="kingkong-item" v-for="item in categoryList" :key="item.id"
				@click="navigateToCategory(item.id)">
				<view class="kingkong-icon">
					<image :src="imgurl+item.icon || '/static/iconfont/category-default.png'" mode="aspectFill"></image>
				</view>
				<text class="kingkong-name">{{item.name}}</text>
			</view>
		</view>

		<!-- 限时抢购 -->
		<view class="time-limited-section">
			<view class="section-left" @click="golink(1)">
				<view class="title-text clor-orige">限时抢购</view>
				<view class="subtitle-text">距离结束</view>
				<view class="countdown">
					<text class="countdown-item">{{countDownData.days||'00'}}</text>
					<text class="countdown-separator">天</text>
					<text class="countdown-item">{{countDownData.hours||'00'}}</text>
					<text class="countdown-separator">:</text>
					<text class="countdown-item">{{countDownData.minutes||'00'}}</text>
					<text class="countdown-separator">:</text>
					<text class="countdown-item">{{countDownData.seconds||'00'}}</text>
				</view>
				<image :src="showImage" mode="aspectFill"></image>
			</view>
			<view class="section-right">
				<view class="section-top">
					<!-- 推荐商品 -->
					<view class="recommend" @click="golink(2)">
						<view class="feature-header">
							<view class="title-text">推荐商品</view>
							<view class="subtitle-text">极致性价比</view>
						</view>
						<image :src="recommendImage" mode="aspectFill"></image>
					</view>
				</view>
				<view class="section-buttom">
					<!-- 促销商品 -->
					<view class="feature-item promotion" @click="golink(3)">
						<view class="title-text">促销商品</view>
						<view class="subtitle-text">限时特惠</view>
						<image :src="promotionImage" mode="aspectFill"></image>
					</view>
					<!-- 常用商品 -->
					<view class="feature-item common" @click="golink(4)">
						<view class="title-text">常用商品</view>
						<view class="subtitle-text">居家必备</view>
						<image :src="commonImage" mode="aspectFill"></image>
					</view>
				</view>
			</view>
		</view>
		<!-- 推荐商品 -->
		<view class="recommendBox" v-if="recommendGoods.length > 0">
			<view class="recommend-title">推荐商品</view>
			<view class="recommend-grid">
				<view class="recommend-item" v-for="item in recommendGoods" :key="item.id"
					@click="navigateToDetail(item.id)">
					<view class="goods-image">
						<image :src="item.thumb || '/static/androidImg/app_logo.png'" mode="aspectFill"></image>
					</view>
					<view class="goods-info">
						<text class="goods-name">{{item.goods_name}}</text>
						<text class="goods-description">{{item.description}}</text>
						<view class="price-container">
							<text class="goods-price">{{item.sell_price}}元</text>
							<text class="goods-unit">/{{item.company}}</text>
						</view>
					</view>
				</view>
			</view>
		</view>
		<!-- 商品列表 -->
		<view class="goods-list-container" :style="{height: windowHeight - 400 + 'px'}">
			<view class="goods-grid">
				<view class="goods-item" v-for="item in goodsList" :key="item.id">
					<view class="goods-image" @click="navigateToDetail(item.id)">
						<image :src="item.thumb" mode="aspectFill"></image>
					</view>
					<view class="goods-info" @click="navigateToDetail(item.id)">
						<view class="goods-main-info">
							<text class="goods-name">{{item.goods_name}}</text>
							<text class="goods-description">{{item.description}}</text>
							<text class="goods-price">{{item.sell_price}}元/{{item.company}}</text>
						</view>
						<view class="goods-stock">
							<text>库存:{{item.num}}</text>
						</view>
					</view>
					<button class="add-cart-btn" type="primary" size="mini" @click="showSpecModal(item)">加入购物车</button>
				</view>
			</view>
			<view class="loading-more" v-if="loadingMore">加载中...</view>
		</view>

		<!-- 规格选择弹窗组件 -->
		<spec-modal v-if="currentGoods" :goods="currentGoods" :show.sync="specModalShow"
			@confirm="handleSpecConfirm"></spec-modal>
	</view>
</template>

<script>
	import api from '../../api/request';
	import specModal from '../../components/specModal.vue';
	export default {
		components: {
			specModal
		},
		data() {
			return {
				windowHeight: 0,
				bannerList: [], // 轮播图数据
				categoryList: [], // 分类数据
				recommendGoods: [], // 推荐商品
				goodsList: [], // 商品列表数据
				timeLimitedGoods: [], // 限时抢购商品
				customerImages: {}, // 客户图片集合
				recommendImage: '/static/androidImg/app_logo.png', // 推荐商品图片默认值
				promotionImage: '/static/androidImg/app_logo.png', // 促销商品图片默认值
				commonImage: '/static/androidImg/app_logo.png', // 常用商品图片默认值
				showImage: '/static/androidImg/app_logo.png', // 限时展示图片默认值
				countDownData: null, // 倒计时数据
				currentPage: 1, // 当前页码
				imgurl: 'https://yuanchu.shangchuapp.com/',
				countDownInterval: null, // 倒计时定时器
				loadingMore: false, // 加载更多状态
				specModalShow: false, // 规格选择弹窗显示状态
				currentGoods: {} // 当前选中的商品
			}
		},
		computed: {},
		onLoad() {
			// 获取窗口高度
			const {
				windowHeight
			} = uni.getSystemInfoSync();
			this.windowHeight = windowHeight;

			// 加载数据
			this.loadHomeData();
		},
		methods: {
			// 加载首页数据
			async loadHomeData() {
				try {
					// 显示加载中
					uni.showLoading({
						title: '加载中...'
					});

					// 并行请求多个接口
					const [bannerRes, categoryRes, recommendRes, goodsRes, countDownRes, customerImageRes] =
					await Promise.all([
						this.$api.getBanner(),
						this.$api.getParentCate(),
						this.$api.getRecommendGoods(),
						this.$api.getGoodsList({
							page: this.currentPage,
							search_word: ''
						}),
						this.$api.getCountDown(),
						this.$api.getCustomerImage()
					]);

					// 更新数据
					this.bannerList = bannerRes.data || [];
					this.categoryList = categoryRes.data || [];
					this.recommendGoods = recommendRes.data || [];
					this.goodsList = goodsRes.data.rows || [];
					// 使用推荐商品数据作为限时抢购商品
					this.timeLimitedGoods = this.recommendGoods.slice(0, 5) || [];
					this.customerImages = customerImageRes.data || {};
					uni.setStorageSync('config', customerImageRes.data)
					// 设置特色区块图片
					this.recommendImage = this.customerImages.tuijian_image || '';
					this.promotionImage = this.customerImages.cuxiao_image || '';
					this.commonImage = this.customerImages.changyong_image || '';
					this.showImage = this.customerImages.xianshi_image || '';

					// 设置倒计时
					if (countDownRes && countDownRes.code === 1) {
						this.startCountDown(countDownRes.data);
					}
				} catch (error) {
					console.error('加载首页数据失败:', error);
					uni.showToast({
						title: error.msg || '加载数据失败',
						icon: 'none'
					});
				} finally {
					// 隐藏加载中
					uni.hideLoading();
				}
			},




			// 上拉加载更多
			onReachBottom() {
				if (!this.loadingMore) {
					this.loadingMore = true;
					this.loadMore();
				}
			},

			// 加载更多数据
			async loadMore() {
				this.currentPage++;
				try {
					const res = await this.$api.getGoodsList({
						page: this.currentPage,
						search_word: ''
					});
					if (res && res.data.rows && res.data.rows.length > 0) {
						this.goodsList = [...this.goodsList, ...res.data.rows];
					} else {
						uni.showToast({
							title: '没有更多数据了',
							icon: 'none'
						});
						this.currentPage--;
					}
				} catch (error) {
					console.error('加载更多失败:', error);
					this.currentPage--;
				} finally {
					this.loadingMore = false;
				}
			},
			// 设置倒计时
			startCountDown(totalSeconds) {
				// 清除之前的定时器
				if (this.countDownInterval) {
					clearInterval(this.countDownInterval);
				}

				// 更新倒计时
				const updateCountDown = () => {
					if (totalSeconds <= 0) {
						this.countDownData = {
							days: '00',
							hours: '00',
							minutes: '00',
							seconds: '00'
						};
						clearInterval(this.countDownInterval);
						return;
					}

					const days = Math.floor(totalSeconds / 86400); // 一天 = 86400秒
					const hours = Math.floor((totalSeconds % 86400) / 3600);
					const minutes = Math.floor((totalSeconds % 3600) / 60);
					const seconds = totalSeconds % 60;

					this.countDownData = {
						days: days.toString().padStart(2, '0'),
						hours: hours.toString().padStart(2, '0'),
						minutes: minutes.toString().padStart(2, '0'),
						seconds: seconds.toString().padStart(2, '0'),
					};

					totalSeconds--;
				};

				// 立即更新一次
				updateCountDown();

				// 设置定时器，每秒更新一次
				this.countDownInterval = setInterval(updateCountDown, 1000);
			},

			// 页面卸载时清除定时器
			onUnload() {
				if (this.countDownInterval) {
					clearInterval(this.countDownInterval);
				}
			},

			// 添加到购物车（已被showSpecModal替代）
			addToCart(item) {
				this.showSpecModal(item);
			},
			// 显示规格选择弹窗
			showSpecModal(item) {
				this.currentGoods = item;
				this.specModalShow = true;
			},
			// 处理规格选择确认事件
			handleSpecConfirm(data) {
				const params = {
					goods_id: data.goods.id,
					num: data.num,
					item: data.spec.id
				};

				this.$api.addCart(params).then(res => {
					if (res.success) {
						uni.showToast({
							title: '加入购物车成功',
							icon: 'success'
						});
					} else {
						uni.showToast({
							title: res.msg || '加入购物车失败',
							icon: 'none'
						});
					}
				}).catch(err => {
					console.log('errerr', err)
					uni.showToast({
						title: err.msg || '网络错误，请重试',
						icon: 'none'
					});
				});
			},
			// 跳转到注册页面（保留此功能，可能通过其他入口访问）
			navigateToRegister() {
				uni.navigateTo({
					url: '/pages/register/register'
				});
			},
			//跳转搜索
			navigateToSearch() {
				uni.navigateTo({
					url: '/pages/index/search'
				})
			},

			//跳转到分类页面
			navigateToCategory(id) {
				// 使用本地存储传递参数
				uni.setStorageSync('categoryId', id);
				// 切换到分类tab
				uni.switchTab({
					url: '/pages/index/category'
				})
			},

			// 跳转到商品详情页
			navigateToDetail(goodsId) {
				uni.navigateTo({
					url: `/pages/goods/detail?goods_id=${goodsId}`
				})
			},
			//跳转
			golink(id) {
				uni.navigateTo({
					url: '/pages/goods/list?id=' + id,
				})
			},
			// 发送给朋友
			onShareAppMessage() {
				return {
					title: this.customerImages.share_title, // 标题
					content: this.customerImages.share_content,
					path: '/pages/index/index', // 要分享的页面
				}
			},
			// 分享到朋友圈
			onShareTimeline() {
				return {
					title: this.customerImages.share_title, // 标题
					content: this.customerImages.share_content,
					path: '/pages/index/index', // 要分享的页面
				}
			},

		}
	}
</script>

<style lang="scss" scoped>
	// 商品列表样式
	.goods-list-container {
		padding: 0 20rpx 20rpx 20rpx;
		// overflow-y: auto;
	}

	.goods-grid {
		display: flex;
		flex-direction: column;
		gap: 20rpx;
	}

	.goods-item {
		display: flex;
		background-color: #fff;
		border-radius: 10rpx;
		overflow: hidden;
		padding: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
		position: relative;

		.goods-image {
			width: 180rpx;
			height: 180rpx;
			margin-right: 20rpx;
			flex-shrink: 0;

			image {
				width: 100%;
				height: 100%;
				display: block;
				border-radius: 8rpx;
			}
		}

		.goods-info {
			flex: 1;
			display: flex;
			justify-content: space-between;

			.goods-main-info {
				flex: 1;

				.goods-name {
					font-size: 28rpx;
					color: #333;
					margin-bottom: 8rpx;
					display: -webkit-box;
					-webkit-box-orient: vertical;
					-webkit-line-clamp: 1;
					overflow: hidden;
				}

				.goods-description {
					font-size: 24rpx;
					color: #666;
					margin-bottom: 12rpx;
					display: -webkit-box;
					-webkit-box-orient: vertical;
					-webkit-line-clamp: 1;
					overflow: hidden;
				}

				.goods-price {
					font-size: 28rpx;
					color: #e64340;
					font-weight: bold;
				}
			}

			.goods-stock {
				display: flex;
				flex-direction: column;
				align-items: flex-end;
				justify-content: center;
				padding-left: 20rpx;

				text {
					font-size: 24rpx;
					color: #999;
				}

				.stock-num {
					font-size: 32rpx;
					color: #333;
					font-weight: bold;
					text-align: right;
				}
			}
		}

		.add-cart-btn {
			position: absolute;
			bottom: 20rpx;
			right: 20rpx;
			background-color: #FE0000;
			color: #fff;
			font-size: 24rpx;
			padding: 0 20rpx;
			height: 50rpx;
			line-height: 50rpx;
			border-radius: 25rpx;
			z-index: 10;
		}
	}

	.loading-more {
		text-align: center;
		padding: 20rpx 0;
		font-size: 24rpx;
		color: #999;
	}

	.container {
		display: flex;
		flex-direction: column;
		height: 100vh;
		background: #f8f8f8;
	}

	/* 搜索框样式 */
	.search-container {
		padding: 10px;
		background-color: #FE0000;
	}

	.search-bar {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 40px;
		background-color: #f5f5f5;
		border-radius: 20px;
		padding: 0 15px;
	}

	.search-bar .iconfont {
		color: #999;
		margin-right: 5px;
	}

	.search-bar .placeholder {
		color: #999;
		font-size: 14px;
	}


	.banner-swiper {
		width: 750rpx;
		height: 350rpx;

		.banner-image {
			width: 750rpx;
			height: 350rpx;
			display: block;
		}
	}

	// 金刚区样式
	.kingkong-container {
		display: flex;
		flex-wrap: wrap;
		padding: 20rpx;
		background-color: #fff;
		border-bottom: 1rpx solid #f0f0f0;

		.kingkong-item {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			width: 25%;
			padding: 15rpx 0;

			.kingkong-icon {
				width: 80rpx;
				height: 80rpx;
				margin-bottom: 10rpx;
				background-color: #f8f8f8;
				border-radius: 50%;
				display: flex;
				align-items: center;
				justify-content: center;

				image {
					width: 80rpx;
					height: 80rpx;
					border-radius: 50%;
					display: block;
				}
			}

			.kingkong-name {
				font-size: 24rpx;
				color: #333;
				text-align: center;
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
			}
		}
	}



	.time-limited-section {
		width: 730rpx;
		margin: 20rpx 0 20rpx 20rpx;
		clear: both;

		.title-text {
			font-size: 34rpx;
		}

		.subtitle-text {
			font-size: 26rpx;
			color: #666;
		}

		.section-left {
			width: 210rpx;
			float: left;
			margin-right: 20rpx;
			border-radius: 10rpx;
			background: #fff;
			padding: 20rpx;

			.countdown {
				display: flex;
				padding: 50rpx 0;
				justify-content: space-evenly;
				align-items: center;

				.countdown-item {
					background: #333;
					color: #fff;
					padding: 0 4rpx;
					border-radius: 10rpx;
					font-size: 22rpx;
					line-height: 40rpx;
				}

				.countdown-separator {
					font-size: 22rpx;
				}
			}

			image {
				width: 120rpx;
				height: 120rpx;
				display: block;
				margin: 10rpx auto 0;
			}
		}

		.section-right {
			width: 460rpx;
			float: left;
			overflow: hidden;

			.recommend {
				display: flex;
				padding: 20rpx;
				border-radius: 10rpx;
				align-items: center;
				justify-content: space-between;
				background: #fff;
				margin-right: 20rpx;
				margin-bottom: 20rpx;

				image {
					width: 100rpx;
					height: 100rpx;
					display: block;
				}
			}

			.section-buttom {
				display: flex;

				.feature-item {
					background: #fff;
					flex: 1;
					padding: 20rpx;
					margin-right: 20rpx;
					border-radius: 10rpx;

					image {
						width: 100rpx;
						height: 100rpx;
						display: block;
						margin: 10rpx auto 0;
					}
				}
			}
		}
	}

	// 推荐商品样式
	.recommendBox {
		padding: 20rpx;
		background-color: #fff;
		margin: 0 20rpx 20rpx 20rpx;
		border-radius: 10rpx;

		.recommend-title {
			font-size: 32rpx;
			font-weight: bold;
			color: #333;
			margin-bottom: 20rpx;
			padding-bottom: 10rpx;
			border-bottom: 1rpx solid #f0f0f0;
		}

		.recommend-grid {
			display: grid;
			grid-template-columns: repeat(3, 1fr);
			gap: 20rpx;
		}

		.recommend-item {
			background-color: #f9f9f9;
			border-radius: 10rpx;
			overflow: hidden;
			padding: 15rpx;

			.goods-image {
				width: 100%;
				height: 180rpx;
				margin-bottom: 15rpx;

				image {
					width: 100%;
					height: 100%;
					display: block;
					border-radius: 8rpx;
				}
			}

			.goods-info {
				padding: 0 5rpx;

				.goods-name {
					font-size: 26rpx;
					color: #333;
					margin-bottom: 8rpx;
					display: -webkit-box;
					-webkit-box-orient: vertical;
					-webkit-line-clamp: 1;
					overflow: hidden;
				}

				.goods-description {
					font-size: 22rpx;
					color: #666;
					margin-bottom: 10rpx;
					display: -webkit-box;
					-webkit-box-orient: vertical;
					-webkit-line-clamp: 1;
					overflow: hidden;
				}

				.price-container {
					display: flex;
					align-items: baseline;

					.goods-price {
						font-size: 28rpx;
						color: #e64340;
						font-weight: bold;
					}

					.goods-unit {
						font-size: 22rpx;
						color: #666;
						margin-left: 5rpx;
					}
				}
			}
		}
	}
</style>